<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="elibrary.*" %>
<%@ page language="java" import="java.util.*"%>
<%@ include file="config.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
    </head>
    <body>

        <%

        //gets the username and password from the session


        String username=request.getParameter("username");
        String password=request.getParameter("password");

        Statement stmt = null;
        ResultSet results = null;
        try{
	
                //Connection is made to the database and the user is validated and if he is a valid user the he is taken to his home page
	
	
                Connection con=DaoConnection.getcon(connectURL, DBuser, DBpass);
                String str ="SELECT * FROM USERS WHERE(USERNAME=? )";
                java.sql.PreparedStatement st = con.prepareStatement(str);
                st.setString(1,username);
                java.sql.ResultSet rs = st.executeQuery();
                DesEncrypter encrypter = new DesEncrypter();
                if(rs.next())
                {
                        String pass = rs.getString("PASSWORD");
                        if(pass.equals(password))
                        {
                                Integer uid1=rs.getInt("uid");
                                String type = encrypter.encrypt(rs.getString("USERTYPE"));
                                String uid=uid1.toString();
                                String encrypted = encrypter.encrypt(uid);
                            session.setAttribute("uid", encrypted);
                            session.setAttribute("type", type);
                            str="UPDATE USERS SET LASTLOGIN=CURRENT TIMESTAMP WHERE UID="+uid1;
                                st = con.prepareStatement(str);
                                st.executeUpdate();
                                response.sendRedirect("home.jsp");
                        }
                        else
                                session.setAttribute("message", "The username or password you entered is invalid.");
                                response.sendRedirect("index.jsp");
                }
                else
                        response.sendRedirect("index.jsp");
        }catch(Exception e){
             out.println(e.toString());
             out.println("ERROR!!");
             e.printStackTrace();
         }
        %>

    </body>
</html>